<template>
    <div class="qilin-treeDepts flex-column">
        <div class="qilin-treeDepts-selected qilin-p-4 qilin-mb-4 flex-column">
            <div class="qilin-treeDepts-selected-text qilin-mb-2">已选择：</div>
            <div class="qilin-treeDepts-selected-list flex-row beauty-scrollbar-y">
                <div class="qilin-treeDepts-selected-list-item qilin-bg-primary qilin-px-4 qilin-mr-6 qilin-mb-3 qilin-radius-default"
                    v-for="item in selectedData"
                >
                    <span>{{ item.label }}</span>
                    <!-- <span class="qilin-ml-2 qilin-text-medium" @click="deleteTreeDataItem(item)">×</span> -->
                </div>
            </div>
        </div>
        <div class="qilin-treeDepts-tree beauty-scrollbar-y">
            <QilinTree v-model:treeConfig="treeConfig" ref="treeConfigRef"></QilinTree>
        </div>
    </div>
</template>

<script setup>
/**
 * Qilin-web选择组织组件封装
 *  已选择中的删除若配合回显来的数据再进行点击删除会出现些许问题，后续再优化，现先去除点击删除功能
 * @author Qilin
 * @CreateDate 2025-01-20
 * @lastUpdateDate 2025-02-13
 */
import {getVisualDept} from "@/api/index.js";



/*
    响应式选项区域
*/
// 暴露父组件自定义方法
const emits=defineEmits(["success"]);


/*
    数据变量定义区域
*/
const treeConfigRef = ref(null); //获取树形元素DOM
let selectedData = ref([]); //已选择的数据


/*
    计算属性等代码区域
*/


/*
    逻辑脚本代码区域
*/
// 初始化加载
const initRenderData=(data)=>{
    selectedData.value = [...data] || [];
    treeConfigRef.value.getCheckedKeys().forEach((item)=>{ //选取消树的选中状态
        treeConfigRef.value.setChecked(item,false,true);
    });
    if(selectedData.value.length > 0){ //取消树形选中状态
        treeConfigRef.value.setCheckedKeys(selectedData.value.map((item)=>item.id));//回显选中
    }
    // console.log(selectedData.value);
};
// 删除已选择的部门组织事件监听
const deleteTreeDataItem=(obj)=>{
    // console.log(obj);
    function getChildrenKey(target) {
        // 获取其父节点
        const parentTarget =
            selectedData.value.find((item) => {
                return item.id === target.parentId;
            }) || {};
        // 判断父节点的children是否只有它一个后代，若是直接删除并继续往上遍历重复此操作
        if (parentTarget.children && parentTarget.children.length === 1) {
            const parentIndex = selectedData.value.findIndex((item) => {
                return item.id === parentTarget.id;
            });
            selectedData.value.splice(parentIndex, 1);
            getChildrenKey(parentTarget);
            // 若不是，则仅删除父节点自身并停止向上遍历
        } else if (parentTarget.children && parentTarget.children.length > 1) {
            const parentIndex = selectedData.value.findIndex(
                (item) => {
                    return item.id === parentTarget.id;
                }
            );
            selectedData.value.splice(parentIndex, 1);
        }
        // 获取自身节点所在索引
        const index = selectedData.value.findIndex((item) => {
            return item.id === target.id;
        });
        if (index !== -1) {
            // 删除己身
            selectedData.value.splice(index, 1);
        }
        // 若有children后代，则删除全部后代且继续向下遍历重复此操作
        if (target.children && target.children.length > 0) {
            for (let i in target.children) {
                getChildrenKey(target.children[i]);
            }
        }
    }
    getChildrenKey(obj);
    // console.log('tree.value', treeRef);
    treeConfigRef.value.setCheckedNodes(selectedData.value);
};
// 确认选择可见范围事件监听
const confirmSelected=()=>{
    // console.log(selectedData.value);
    emits("success",selectedData.value);
};
// 初始化获取部门组织数据事件监听
const getVisualDeptData=()=>{
    getVisualDept().then((res)=>{
        if(res.code === 200){
            console.log(res);
            treeConfig.data = res.data;
            treeConfig.itemConfig.defaultExpandedKeys = [res.data[0].id];
        }else{
            ElMessage({
                message:res.msg || "系统错误",
                type:"error"
            });
        }
    });
};

// 树形配置项
const treeConfig = reactive({
    itemConfig:{
        nodeKey:"id",
        showCheckbox:true,
        // checkStrictly:true,
        defaultCheckedKeys:[],
        defaultExpandedKeys:[],
        check:(nodeObj, treeStatusObj)=>{
            // console.log(nodeObj,treeStatusObj);
            selectedData.value = treeStatusObj.checkedNodes;
        }
    },
    props:{
        label:"label",
        children:"children"
    },
    data:[]
});


/*
    生命周期等代码区域
*/
getVisualDeptData();

defineExpose({
    initRenderData,
    confirmSelected
});


</script>

<style lang="scss" scoped>
.qilin-treeDepts{
    max-height:3.5rem;
    >.qilin-treeDepts-selected{
        height:1rem;
        border:1px dashed var(--qilin-border-color);
        >.qilin-treeDepts-selected-list{
            flex:1;
            flex-wrap: wrap;
            align-items:baseline;
            >.qilin-treeDepts-selected-list-item{
                height:auto;
                cursor:pointer;
            }
        }
    }
    >.qilin-treeDepts-tree{
        flex:1;
        min-height:0;
        border:1px dashed var(--qilin-border-color);
    }
}
</style>
